from flask import Blueprint, request, current_app
from flask_json import as_json
from flask_jwt_extended import jwt_required
from werkzeug.security import generate_password_hash

from app import db
from .is_staff_user import is_staff_user
from app.auth.auth_decorator import has_role
from app.models import CommonResult, CommonPage, BlogUser
from app.form.register_form import RegisterForm
from app.form.user_update_form import UserUpdateForm
from app.common.enums import RoleCodeEnum

log = current_app.logger
admin_user = Blueprint('admin_user', __name__, url_prefix='/admin/user')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(admin_user)


# 分页查询用户列表
@admin_user.post('/page')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def page():
    data = request.get_json()
    current = 1
    page_size = 10
    page_obj = BlogUser.query
    # 如果传入查询参数，就筛选数据
    if data:
        current = data.get('current') or 1
        page_size = data.get('page_size') or 10
        username = data.get('username')
        super_user = data.get('super_user')
        active_user = data.get('active_user')
        staff_user = data.get('staff_user')
        # 筛选数据
        if username:
            page_obj = page_obj.filter(BlogUser.username.like('%{keyword}%'.format(keyword=username)))
        if super_user is not None:
            page_obj = page_obj.filter(BlogUser.super_user == super_user)
        if active_user is not None:
            page_obj = page_obj.filter(BlogUser.active_user == active_user)
        if staff_user is not None:
            page_obj = page_obj.filter(BlogUser.staff_user == staff_user)
    # 分页查询
    # error_out：查不到提示404，默认开启
    page_data = page_obj.paginate(
        page=current,
        per_page=page_size,
        error_out=False
    )
    return CommonResult(data=CommonPage(page_data))


# 获取详情
@admin_user.get('/get/<int:user_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def info(user_id):
    user = BlogUser.query.get(user_id)
    if user:
        return CommonResult(data=user, msg='获取成功')
    else:
        return CommonResult(code=500, msg='用户不存在')


# 添加用户
@admin_user.post('/add')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def add():
    RegisterForm().api_validate()
    data = request.get_json()
    # 填充数据
    user = BlogUser()
    user.__dict__.update(data)
    # 加密密码
    user.password = generate_password_hash(data.get('password'))
    # 保存数据库
    db.session.add(user)
    db.session.commit()
    return CommonResult(data=data, msg='保存成功')


# 修改用户信息
@admin_user.post('/update')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def update():
    UserUpdateForm().api_validate()
    data = request.get_json()
    # 更新用户信息
    user_id = int(data.get('id'))
    db.session.query(BlogUser).filter(BlogUser.id == user_id).update(data)
    db.session.commit()
    return CommonResult(data=data, msg='修改成功')


# 删除记录
@admin_user.get('/delete/<int:user_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def delete(user_id):
    # 查询用户是否存在
    user = BlogUser.query.get(user_id)
    if user is None:
        return CommonResult(code=500, msg='删除的用户不存在')
    # 删除记录
    db.session.delete(user)
    db.session.commit()
    return CommonResult(msg='删除成功')


# 重置密码
@admin_user.get('/reset_password/<int:user_id>')
@jwt_required()
@has_role({RoleCodeEnum.ADMIN})
@is_staff_user
@as_json
def reset_password(user_id):
    # 查询用户是否存在
    user = BlogUser.query.get(user_id)
    if user is None:
        return CommonResult(code=500, msg='用户不存在')
    # 重置密码
    user.password = generate_password_hash('123456')
    db.session.commit()
    return CommonResult(data='123456', msg='密码已重置为：123456，请及时修改！')
